package main

import (
	"fmt"
	"net/http"
	"reflect"
	"runtime"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "hello %s", r.URL.Path[1:])
}

/**
 * logPrint和hello同为处理器函数，想要两个都执行，就要把一个处理器函数当做参数传递给另一个处理器，函数参数类型指定http.HandlerFunc
 * 用法：主程序绑定logPrint函数，将hello函数传递给logPrint，logPrint在最终返回的处理器函数里加了额外操作，然后执行传入的hello方法
 */
func logPrint(h http.HandlerFunc) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		name := runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name()
		fmt.Println("Handler function called -" + name)
		h(writer, request)
	}
}

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/hello/", logPrint(hello))
	server.ListenAndServe()
}
